package ttOrder.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ttOrder.model.DinnerTable;

@Repository
public class TableDAOImpl extends BaseHibernateDAO<DinnerTable> implements ITableDAO {
	@Autowired
	private SessionFactory sessionFactory;

	public Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}

	@Override
	public List<DinnerTable> findAllTable() {

		Session session = getSession();
		String hql = "from DinnerTable";
		@SuppressWarnings("unchecked")
		List<DinnerTable> table = session.createQuery(hql).list();
		return table;
	}

	@Override
	public DinnerTable getTableById(Integer id) {
		Session session = getSession();
		return (DinnerTable) session.get(DinnerTable.class, id);
	}

	@Override
	public Integer createTable(DinnerTable table) throws Exception {
		Session session = getSession();
		table.setTablestatus(0);
		session.save(table);
		return null;
	}

	@Override
	public Integer editTable(Integer id) throws Exception {
		Session session = getSession();
		DinnerTable table = (DinnerTable) session.get(DinnerTable.class, id);
		if (table != null) {
			if (table.getTablestatus() == 1) {

				table.setTablestatus(0);
				table.setOrderdate(null);
			} else if (table.getTablestatus() == 0) {
				Date now = new Date();
				table.setTablestatus(1);
				table.setOrderdate(now);
			}

		}
		return null;
	}

	@Override
	public Integer deleteTable(Integer id) throws Exception {
		Session session = getSession();
		DinnerTable table = (DinnerTable) session.get(DinnerTable.class, id);

		if (table != null) {
			session.delete(table);

		}
		return null;
	}

}
